package com.wiretrack.circuit;

import java.awt.EventQueue;

import javax.swing.JFrame;
import java.awt.BorderLayout;

import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

public class App
{
	private static Logger log = Logger.getLogger(App.class.getName());

	private static JFrame frmWorkout;
	private com.wiretrack.circuit.CountdownManager countDownmanager = null;
	private static Configuration configurationFile = null;
//	private static String workoutXMLFileToUse = "./src/test/resources/config1.xml";
//	private static String workoutXMLFileToUse = "./src/test/resources/plyometrics.xml";
//	private static String workoutXMLFileToUse = "./src/test/resources/12_round_circuit.xml";
	private static String workoutXMLFileToUse = null;
	// private static String configFile =
	// "./src/test/resources/plyometrics.xml";

	static
	{
		try
		{
			if ( workoutXMLFileToUse != null && workoutXMLFileToUse.length() > 0 )
				configurationFile = Configuration.getInstance(workoutXMLFileToUse);
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch (DocumentException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * Launch the application.
	 */
	public static void main(String[] args)
	{
		Options options = new Options();
		Option help = new Option("help", "print this message");
		Option workoutXMLFile = OptionBuilder.withArgName("file").hasArg().withDescription("use given buildfile")
				.create("file");

		options.addOption(help);
		options.addOption(workoutXMLFile);

		CommandLineParser parser = new BasicParser();
		String fileToUse = null;

		try
		{
			CommandLine line = parser.parse(options, args);

			if ( line.hasOption("file") )
			{
				fileToUse = line.getOptionValue("file");
				log.debug("Using workout file: " + fileToUse);

				configurationFile = Configuration.getInstance(fileToUse);
			}
			else
			{
				log.debug("No file defined");
			}
		}
		catch (ParseException exp)
		{
			System.err.println("Parsing failed.  Reason: " + exp.getMessage());
		}
		catch (MalformedURLException e)
		{
			log.error("Invalid file: " + fileToUse);
		}
		catch (DocumentException e)
		{
			log.error("Invalid file: " + fileToUse);
		}

		EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				try
				{
					App window = new App();
					if(configurationFile != null)
					{
						frmWorkout.setBounds(100, 100, configurationFile.windowWidth, configurationFile.windowHeigth);
					}
					
					window.frmWorkout.setVisible(true);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public App()
	{
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize()
	{
		frmWorkout = new JFrame();
		frmWorkout.getContentPane().setBackground(new Color(220, 220, 220));
		
//		frmWorkout.setBackground(Color.LIGHT_GRAY);
//		frmWorkout.getContentPane().setForeground(Color.WHITE);
		log.debug("SHOULD set to yellow?");
		frmWorkout.getContentPane().setBackground(Color.YELLOW);
		
		frmWorkout.setTitle("Spun Munkey Workout System");
//		frmWorkout.setForeground(Color.BLACK);
		frmWorkout.setBounds(100, 100, 423, 306);
		frmWorkout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmWorkout.getContentPane().setLayout(new BorderLayout(0, 0));

		final JPanel namePanel = new JPanel();
		frmWorkout.getContentPane().add(namePanel, BorderLayout.CENTER);
		namePanel.setLayout(new BorderLayout(0, 0));

		final JPanel progressBarPanel = new JPanel();
		namePanel.add(progressBarPanel, BorderLayout.SOUTH);

		final JLabel nextLabel = new JLabel("");
		nextLabel.setForeground(Color.LIGHT_GRAY);
		nextLabel.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 20));
		nextLabel.setHorizontalAlignment(SwingConstants.CENTER);
		progressBarPanel.add(nextLabel);

		final SwingLabel swingNextLabel = new SwingLabel(nextLabel);

		final JLabel nameLabel = new JLabel("SpunXT2");
		nameLabel.setFont(new Font("Dialog", Font.BOLD, 38));
		nameLabel.setHorizontalAlignment(SwingConstants.CENTER);
		namePanel.add(nameLabel, BorderLayout.NORTH);
		if(configurationFile != null)
			namePanel.setBackground(configurationFile.getBackgroundColor());
		
		final SwingLabel swingNameLabel = new SwingLabel(nameLabel);

		final JPanel mainTimerPanel = new JPanel();
		namePanel.add(mainTimerPanel, BorderLayout.CENTER);
		mainTimerPanel.setLayout(new BorderLayout(0, 0));
		if(configurationFile != null)
			mainTimerPanel.setBackground(configurationFile.getBackgroundColor());
		

		final JLabel descriptionLabel = new JLabel("Select Workout");
		descriptionLabel.setForeground(new Color(0, 0, 0));
		descriptionLabel.setFont(new Font("Dialog", Font.BOLD, 24));
		descriptionLabel.setHorizontalAlignment(SwingConstants.CENTER);
		mainTimerPanel.add(descriptionLabel, BorderLayout.SOUTH);

		final SwingLabel swingDescriptionLabel = new SwingLabel(descriptionLabel);

		final JLabel timeLabel = new JLabel("0:00");
		timeLabel.setForeground(new Color(0, 0, 0));
		timeLabel.setFont(new Font("Bitstream Charter", Font.BOLD, 99));
		timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
		mainTimerPanel.add(timeLabel, BorderLayout.CENTER);

		final SwingLabel swingTimeLabel = new SwingLabel(timeLabel);

		final JProgressBar progressBar = new JProgressBar();
		progressBar.setToolTipText("Shows status of workout");
		progressBar.setStringPainted(true);
		frmWorkout.getContentPane().add(progressBar, BorderLayout.SOUTH);
		progressBar.setVisible(false);

		final SwingProgressBar swingProgressBar = new SwingProgressBar(progressBar);

		JMenuBar menuBar = new JMenuBar();
		frmWorkout.setJMenuBar(menuBar);

		JMenu mnMenu = new JMenu("Go");
		mnMenu.setMnemonic('g');
		menuBar.add(mnMenu);

		JMenuItem mntmOpen = new JMenuItem("Open");
		mntmOpen.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				System.out.println("Open");
				final JFileChooser fc = new JFileChooser();
				int returnVal = fc.showOpenDialog(frmWorkout);

				if ( returnVal == JFileChooser.APPROVE_OPTION )
				{
					File file = fc.getSelectedFile();
					try
					{
						System.out.println("Opening: " + file.getCanonicalPath());
						Color[] colors = new Color[3];
						colors[0] = Color.YELLOW;
						colors[1] = Color.ORANGE;
						colors[2] = Color.CYAN;
//						ScreenFlasher bc = new ScreenFlasher(mainTimerPanel, namePanel, colors);

						configurationFile = Configuration.getInstance(file.getCanonicalPath());
						
						countDownmanager = new CountdownManager(configurationFile, swingTimeLabel, swingNameLabel,
								swingDescriptionLabel, swingNextLabel, swingProgressBar, mainTimerPanel, namePanel);
						
						frmWorkout.setTitle("Spun Munkey Workout System - " + configurationFile.name);
						progressBar.setVisible(true);
					}
					catch (IOException e1)
					{
						e1.printStackTrace();
					}
					catch (DocumentException de)
					{
						de.printStackTrace();
					}
				}
				else
				{
					System.out.println("Open command cancelled by user.");
				}
			}
		});
		mnMenu.add(mntmOpen);

		JMenuItem mntmStart = new JMenuItem("Start");
		mntmStart.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				log.debug("Starting...");
//				Color[] colors = new Color[3];
//				colors[0] = Color.YELLOW;
//				colors[1] = Color.ORANGE;
//				colors[2] = Color.CYAN;
//				ScreenFlasher bc = new ScreenFlasher(mainTimerPanel, namePanel, colors);

				countDownmanager = new CountdownManager(configurationFile, swingTimeLabel, swingNameLabel,
						swingDescriptionLabel, swingNextLabel, swingProgressBar, mainTimerPanel, namePanel);
				
				frmWorkout.setTitle("Spun Munkey Workout System - " + configurationFile.name);
				progressBar.setVisible(true);
				countDownmanager.start();
			}
		});
		mnMenu.add(mntmStart);

		JMenuItem mntmStop = new JMenuItem("Stop");
		mntmStop.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				System.out.println("Stop");
			}
		});
		mnMenu.add(mntmStop);

		JMenuItem mntmPause = new JMenuItem("Pause");
		mntmPause.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				System.out.println("Pause");
				countDownmanager.pause(true);
			}
		});
		mnMenu.add(mntmPause);

		JMenuItem mntmExit = new JMenuItem("Exit");
		mntmExit.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				System.out.println("Exit");
				System.exit(0);
			}
		});

		JMenuItem mntmResume = new JMenuItem("Resume");
		mntmResume.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				System.out.println("Resume");
				countDownmanager.pause(false);
			}
		});
		mnMenu.add(mntmResume);

		JMenuItem mntmTheme = new JMenuItem("Theme");
		mntmTheme.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				nextLabel.setForeground(Color.BLUE);
				timeLabel.setForeground(Color.GREEN);
				Color[] colors = new Color[3];
				colors[0] = Color.YELLOW;
				colors[1] = Color.ORANGE;
				colors[2] = Color.CYAN;
//				ScreenFlasher bc = new ScreenFlasher(mainTimerPanel, namePanel, colors);
//				bc.start();
			}
		});
		mnMenu.add(mntmTheme);
		mnMenu.add(mntmExit);
		
		if(configurationFile != null)
		{
			log.debug("Starting...");
//			Color[] colors = new Color[3];
//			colors[0] = Color.YELLOW;
//			colors[1] = Color.ORANGE;
//			colors[2] = Color.CYAN;
//			ScreenFlasher bc = new ScreenFlasher(mainTimerPanel, namePanel, colors);

			countDownmanager = new CountdownManager(configurationFile, swingTimeLabel, swingNameLabel,
					swingDescriptionLabel, swingNextLabel, swingProgressBar, mainTimerPanel, namePanel);
			
			progressBar.setVisible(true);
			countDownmanager.start();
		}
	}
}
